package com.xzq.bustack.netty;

import com.sun.org.apache.regexp.internal.RE;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/20 12:23
 * @Version 1.0.0
 **/
@Component
public class NettyServer {

    private Logger logger = LoggerFactory.getLogger(NettyServer.class);

    //配置服务端NIO线程组
    private final NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    private final NioEventLoopGroup wokerGroup = new NioEventLoopGroup();
    private Channel channel;

    public ChannelFuture lister(InetSocketAddress address) {
        ChannelFuture channelFuture = null;
        try {
            ServerBootstrap b = new ServerBootstrap()
                    .group(bossGroup, wokerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childHandler(new MyChannelInitializer());
            channelFuture = b.bind(address).syncUninterruptibly();
            channel = channelFuture.channel();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != channelFuture && channelFuture.isSuccess()) {
                logger.info("Netty Server Start Success");
            } else {
                logger.error("Netty Server start error");
            }
        }
        return channelFuture;
    }

    public void destroy() {
        if (null==channel){return;}
        channel.closeFuture();
        bossGroup.shutdownGracefully();
        wokerGroup.shutdownGracefully();
    }

    public Channel getChannel() {
        return channel;
    }
}
